import {
  app,
  shell,
  BrowserWindow,
  ipcMain,
  Menu,
  Notification,
  dialog,
  Tray,
  nativeTheme
} from 'electron'
import { join, path } from 'path'

import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
let mainWindow
function createWindow() {
  // Create the browser window.
  // frame 定义无边框窗口
  mainWindow = new BrowserWindow({
    frame: false,
    alwaysOnTop: true,
    resizable: false,
    // titleBarStyle: 'hidden',

    skipTaskbar: false,
    transparent: true,
    width: 80,
    height: 64,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  let contextMenu = Menu.buildFromTemplate([
    { label: '重新加载' || 'test', role: 'reload' },
    { label: '退出', accelerator: 'ctrl+Esc', role: 'quit' },
    {
      label: '关于',
      submenu: [
        { label: '系统菜单', role: 'windowMenu' },
        { label: '开发者工具', role: 'viewMenu' },
        { label: '检查更新', role: 'checkUpdate' },

        { label: '工具栏', role: 'toggleDevTools' },

        { label: '退出', accelerator: 'ctrl+Esc', role: 'quit' },

        { label: '全屏', accelerator: 'ctrl+F11', role: 'togglefullscreen' }
      ]
    },
    { label: 'Item 3', type: 'separator' },
    {
      label: 'Item 4',
      onclick: function () {
        console.log('item 4')
        //  new Notification({ title: 'NOTIFICATION_TITLE', body: 'NOTIFICATION_BODY' }).show()
      }
    },
    {
      role: 'help',
      submenu: [
        {
          label: 'Learn More',
          click: async () => {
            const { shell } = require('electron')
            await shell.openExternal('https://electronjs.org')
          }
        }
      ]
    }
  ])

  // 右键菜单
  mainWindow.webContents.on('context-menu', (e, params) => {
    console.log(e, params)
    contextMenu.popup()
  })
  // 打开开发工具
  //mainWindow.openDevTools()

  // 忽略鼠标事件

  /*mainWindow.setIgnoreMouseEvents(true, {
    forward: true
  })*/
  // mainWindow.setSkipTaskbar(true) // 无任务栏图标
  //mainWindow.setMenu(null)
  //ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
  // const win = BrowserWindow.fromWebContents(event.sender)
  //  win.setIgnoreMouseEvents(ignore, options)
  //})

  // mainWindow.setIgnoreMouseEvents(true)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, icon))
  }
  // 隐藏菜单栏
  Menu.setApplicationMenu(null) //windows

  app.dock.hide() //macos
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

ipcMain.handle('dark-mode:toggle', () => {
  if (nativeTheme.shouldUseDarkColors) {
    nativeTheme.themeSource = 'light'
  } else {
    nativeTheme.themeSource = 'dark'
  }
  return nativeTheme.shouldUseDarkColors
})

ipcMain.handle('dark-mode:system', () => {
  nativeTheme.themeSource = 'system'
})
//await window.darkMode.toggle()

// 打开子窗口
//var childWin;  // 把childWin设置在函数外面和设置在函数里面效果不一样！
// 判断开发环境
const winURL =
  process.env.NODE_ENV === 'development'
    ? 'http://localhost:5173'
    : `file://${__dirname}/index.html`

function openChildWindow(param) {
  console.log('openChildWindow', param)
  console.log(__dirname)
  console.log(winURL + '#' + param.url)
  // 创建窗口
  var childWin = new BrowserWindow({
    width: param.width ? param.width : 800,
    height: param.height ? param.height : 600,
    parent: mainWindow // win是主窗口，不加parent，新建的窗口将于主窗口平级
    //  webPreferences: {
    //   nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
    //   contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    //  preload: path.resolve(__dirname, '../preload.js')
    // preload: join(__dirname, '../preload/child.js')
    // }
  })

  childWin.loadURL(winURL + '#' + param.url) // hash路由
  // childWin.loadURL(param.url) // hash路由
  childWin.webContents.openDevTools()

  childWin.on('closed', () => {
    childWin = null
  })
}

ipcMain.handle('on-open-event', (e, param) => {
  openChildWindow(param)
})
